package com.eu.mybatis.interceptor;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;

import com.eu.mybatis.config.Dialect;
import com.eu.mybatis.config.InterceptorConfig;
import com.eu.mybatis.helper.InterceptorHelper;
import com.eu.mybatis.partition.PartitionHandler;

@Intercepts({ @org.apache.ibatis.plugin.Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class EuMybatisInterceptor implements Interceptor {

	private static PartitionHandler partitionHandler = new PartitionHandler();

	private Dialect dialect;
	
	public void setDialect(Dialect dialect) {
		this.dialect = dialect;
	}

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		//1、初始化mybatis解析参数
		InterceptorConfig interceptorConfig = new InterceptorConfig(invocation, dialect);
		//2、分表SQL处理
		partitionHandler.handle(interceptorConfig);
		//3、日志记录
		InterceptorHelper.logExecuteSql(interceptorConfig);
		//4、设置totalRows
		interceptorConfig.setTotalRows(invocation);
		//5、重新设置物理分页
		interceptorConfig.resetLogicPageSql();
		return invocation.proceed();
	}

	/**
	 * 当目标类是StatementHandler类型时，才包装目标类，否者直接返回目标本身,减少目标被代理的次数
	 */
	public Object plugin(Object target) {
//		if (target instanceof StatementHandler) {
//			return Plugin.wrap(target, this);
//		} else {
//			return target;
//		}
		return target;
	}

	public void setProperties(Properties properties) {

	}

}
